import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:state_manager/view_model/counter_view_model.dart';

main() {
  runApp(ChangeNotifierProvider(
    child: DBJApp(),
    create: (cxt) {
      return DBJCounterViewModel();
    },
  ));
}

class DBJApp extends StatelessWidget {
  const DBJApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primaryColor: Colors.orange, splashColor: Colors.transparent),
      home: DBJHomePage(),
    );
  }
}

class DBJHomePage extends StatefulWidget {
  const DBJHomePage({Key? key}) : super(key: key);

  @override
  _DBJHomePageState createState() => _DBJHomePageState();
}

class _DBJHomePageState extends State<DBJHomePage> {
  @override
  Widget build(BuildContext context) {
    print("_DBJHomePageState --- build");
    return Scaffold(
      appBar: AppBar(
        title: Text('打扮家'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            DBJCardWidget(),
            DBJContainerWidget(),
          ],
        ),
      ),
      floatingActionButton: Selector<DBJCounterViewModel, DBJCounterViewModel>(
        selector: (cxt, viewModel1) {
          return viewModel1;
        },
        shouldRebuild: (prev, next) => false,
        builder: (cxt, viewModel2, child) {
          print('floatingActionButton --- builder');
          return FloatingActionButton(
            child: child,
            onPressed: () {
              print("++++");
              viewModel2.counter += 1;
            },
          );
        },
        child: Icon(
          Icons.add,
          color: Colors.white,
        ),
      ),
    );
  }
}

class DBJCardWidget extends StatelessWidget {
  const DBJCardWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print("DBJCardWidget --- build");
    return Card(
      color: Colors.purple,
      child: Consumer<DBJCounterViewModel>(
        builder: (cxt, viewModel, child) {
          print("Card --- Consumer --- build");
          return Text(
            '当前计数：${viewModel.counter}',
            style: TextStyle(fontSize: 20, color: Colors.white),
          );
        },
      ),
    );
  }
}

class DBJContainerWidget extends StatelessWidget {
  const DBJContainerWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print("DBJContainerWidget --- build");
    return Container(
      color: Colors.orange,
      child: Consumer<DBJCounterViewModel>(
        builder: (cxt, viewModel, child) {
          print("Container --- Consumer --- build");
          return Text(
            '当前计数：${viewModel.counter}',
            style: TextStyle(fontSize: 20, color: Colors.white),
          );
        },
      ),
    );
  }
}
